class TeachersController < ApplicationController
	def create
		p "params: #{params.inspect}"
		@user = User.new(params[:user])
		p "#{@user.inspect}"
		@user.role = USER_ROLE_STATUS[:teacher]
		p "ff #{@user.inspect}"
	    respond_to do |format|
	      if @user.save
	        flash[:notice] = 'User was successfully created.'
	        format.html { redirect_to(@user) }
	        format.xml  { render :xml => @user, :status => :created, :location => @user }
	      else
	        format.html { render :action => "new" }
	        format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }
	      end
	    end				
	end

	def index
		user_id = params[:user_id]
		questions = Question.teacher_questions(user_id) 
		questions = questions.collect{|question| 
			attrs = question.attributes
			attrs[:student_name] = question.user.user_name
			attrs[:grade_name] = question.grade.name 
			attrs[:subject_name] = question.subject.name			
			attrs
		}
		render :json => questions
	end

	def teacher_answered
		question_id = params[:question_id].to_i
		student_id = params[:student_id].to_i

		users = Question.question(question_id).teacher_answered_for_student(student_id)
		users = users.collect{|user|
			attrs = user.attributes			
			attrs
		}
		render :json => users
	end

	def unanswered
		user_id = User.find(params[:user_id])
		question_count = Question.teacher_questions(user_id).count
		answered_question_count = Question.teacher_answered_questions(user_id).count
		unswered_question_count = question_count - answered_question_count
		render :json => {:count => unswered_question_count}
	end

	def accept
		teacher_id = params[:teacher_id]
		question_id = params[:question_id]
		question = Question.find(question_id)
		question.status = QUESTION_STATUS[:accepted]
		question.save
		user = User.find(teacher_id)
		user.point = user.point || 0
		user.point += 300
		render :json => {:success => 'ok'}
	end

	def withdraw
		teacher_id = params[:user_id]
		code = params[:transfer_code]
		point = params[:amount].to_i

		user = User.find(teacher_id)
		begin
			if code == '123456'
				
				user.point -= point
				point = user.point
				user.save	
			else
				point = user.point			
			end
		rescue Exception => ex
			point = user.point
		end
		render :json => {:point => point}
	end
end
